package com.step.sprite.animation;

import android.util.FloatMath;

import com.step.mesh.Coordinate;

public class KeyFrameMd2 extends KeyFrame{
	private float[] vertices;
	private float[] normals;

	private int[] indices;
	
	public KeyFrameMd2(String name, float[] vertices){
		this.name = name;
		this.vertices = vertices;
	}

	public KeyFrameMd2(String name, float[] vertices, float[] normals)
	{
		this(name, vertices);
		this.normals = normals;
	}
	
	public String getName() {
		return name;
	}

	public float[] getVertices() {
		return vertices;
	}

	public int[] getIndices() {
		return indices;
	}

	public float[] getNormals() {
		return normals;
	}
	
	public void setIndices(int[] indices) {
		this.indices = indices;
		float[] compressed = vertices;
		vertices = new float[indices.length*3];
		int len = indices.length;
		int vi = 0;
		int ii = 0;
		int normalIndex = 0;
		
		for(int i=0; i<len; i++)
		{
			ii = indices[i] * 3;
			vertices[vi++] = compressed[ii];
			vertices[vi++] = compressed[ii + 1];
			vertices[vi++] = compressed[ii + 2];
		}
		
		normals = new float[vertices.length];
		int vertLen = vertices.length;
		
		for(int i=0; i<vertLen; i+=9)
		{
			Coordinate normal = calculateFaceNormal(
					new Coordinate(vertices[i], vertices[i+1], vertices[i+2]),
					new Coordinate(vertices[i+3], vertices[i+4], vertices[i+5]),
					new Coordinate(vertices[i+6], vertices[i+7], vertices[i+8])
					);
			normals[normalIndex++] = normal.getX();
			normals[normalIndex++] = normal.getY();
			normals[normalIndex++] = normal.getZ();
			normals[normalIndex++] = normal.getX();
			normals[normalIndex++] = normal.getY();
			normals[normalIndex++] = normal.getZ();
			normals[normalIndex++] = normal.getX();
			normals[normalIndex++] = normal.getY();
			normals[normalIndex++] = normal.getZ();
		}
	}
	
	public Coordinate calculateFaceNormal(Coordinate v1, Coordinate v2, Coordinate v3)
	{
		Coordinate vector1 = Coordinate.subtract(v2, v1);
		Coordinate vector2 = Coordinate.subtract(v3, v1);
		float normalx = (vector1.getY() * vector2.getZ()) - (vector1.getZ() * vector2.getY());
		float normaly = -((vector2.getZ() * vector1.getX()) - (vector2.getX() * vector1.getZ()));
		float normalz = (vector1.getX() * vector2.getY()) - (vector1.getY() * vector2.getX());
		
		double normFactor = FloatMath.sqrt((normalx * normalx) + (normaly * normaly) + (normalz * normalz));
		
		normalx /= normFactor;
		normaly /= normFactor;
		normalz /= normFactor;
		Coordinate normal = new Coordinate(normalx,normaly,normalz);
		return normal;
	}
	
	public KeyFrameMd2 clone(){
		KeyFrameMd2 k = new KeyFrameMd2(name, vertices.clone(), normals.clone());
		return k;
	}
}
